/*
 * @Author: liuzibin
 * @Date: 2023-07-24 00:34:10
 * @Descroption: 余额支付
 */
const axios = require("axios");
const crypto = require("crypto");

async function balancePay({ cartId, uid, userToken, addressId }) {
  const useIntegral = false; //是否积分混合支付？

  const response = await axios.post(
    `https://borderclear.cn/api/v2/order/create`,
    {
      cart_id: [cartId], // 购物车id
      address_id: addressId, //地址id
      use_coupon: {
        // 0: [],
        // 6: [],
      },
      pay_type: "balance",
      mark: {},
      order_type: 0, // 0.普通 1.自提
      key: createKey({
        cartId,
        useIntegral,
        addressId,
        uid,
      }), // 加密key
      takes: [],
      use_integral: useIntegral,
      // receipt_data: {},
      extend: [],
      // post: {
      //   real_name: "liu",
      //   phone: "13779904086",
      // },
      // return_url: "http://localhost:8080/pages/users/order_list/index",
    },
    {
      headers: {
        Accept: "application/json, text/plain, */*",
        Referer: "http://borderclear.cn/admin/merchant/list",
        "X-Token": userToken,
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
        "Content-Type": "application/json;charset=UTF-8",
      },
    }
  );
  console.log(response.data);

  return response.data.data.result.order_id;
}

// PHP加密逻辑  md5(json_encode(compact('cartId', 'useIntegral', 'addressId'))) .  $user->uid;
function createKey({ cartId, useIntegral, addressId, uid }) {
  const data = JSON.stringify({ cartId, useIntegral, addressId });
  const key = crypto
    .createHash("md5")
    .update(data + uid)
    .digest("hex");

  return key;
}
const uid = "exampleUserId";

module.exports = balancePay;
